using System;
using System.Collections;
using System.Text;
using System.Web;
using LBSoft.Common.DotNetEncrypt;

namespace LBSoft.Common.DotNetUI
{
    public class WebHelper
    {
        /// <summary>
        /// 获取查询条件
        /// </summary>
        /// <returns>SQL语句</returns>
        public static string GetCondition(HttpRequest request)
        {
            StringBuilder condition = new StringBuilder(" where 1=1 ");
            string[] reqallkeys = request.Params.AllKeys;//获取所有参数集合
            foreach (string item in reqallkeys)
            {
                string requestValue = HttpContext.Current.Server.UrlDecode(request[item]).Trim().Replace("'", "");
                string ParamName = string.Empty;

                //约定 s_0_开头的使用 或 like 如request["s_0_ProjectName|ProjectAddress|ConstructUnitName']
                if (item.Contains("s_0_") && !string.IsNullOrEmpty(requestValue))
                {
                    ParamName = item.Replace("s_0_", "");//获取字段名称
                    string[] newParamName;
                    if (ParamName.Contains("|")) //判断是否多个字段查询 or 语句
                    {
                        newParamName = ParamName.Split('|');
                        condition.Append(" and (");
                        foreach (string newitem in newParamName)
                        {
                            if (!string.IsNullOrEmpty(newitem))
                            {
                                if (newitem != newParamName[0]) //如果不是第一个，则sql语句加上 or
                                    condition.Append(" or ");

                                condition.AppendFormat("  {0} like '%{1}%' ", newitem, requestValue);
                            }

                        }
                        condition.Append(" ) ");
                    }
                    else
                    {
                        //单字段
                        condition.AppendFormat(" AND {0} like '%{1}%'", ParamName, requestValue);
                    }
                }
                //约定 s_1_开头的使用 = 号 如request["s_1_ProjectStatus"]
                if (item.Contains("s_1_") && !string.IsNullOrEmpty(requestValue))
                {
                    ParamName = item.Replace("s_1_", "");//获取字段名称
                    condition.AppendFormat(" AND {0}='{1}'", ParamName, requestValue);
                }
                //约定 s_2_开头的使用 like 号 如request["s_2_ProjectName"]
                else if (item.Contains("s_2_") && !string.IsNullOrEmpty(requestValue))
                {
                    ParamName = item.Replace("s_2_", "");//获取字段名称
                    condition.AppendFormat(" AND {0} like '%{1}%'", ParamName, requestValue);
                }
                //约定 s_3_开头的使用 时间比较 如request["s_3_REGISTERDATE"]
                else if (item.Contains("s_3_") && !string.IsNullOrEmpty(requestValue))
                {
                    ParamName = item.Replace("s_3_", "");//获取字段名称
                    if (requestValue.Contains(","))
                    {
                        string[] dateStrs = requestValue.Split(',');
                        condition.Append(GetDateSql(dateStrs[0], dateStrs[1], ParamName));
                    }
                }
                //约定 s_4_开头的使用 数值比较号 如request["s_4_ProjectCost"]
                else if (item.Contains("s_4_") && !string.IsNullOrEmpty(requestValue))
                {
                    ParamName = item.Replace("s_4_", "");//获取字段名称
                    if (requestValue.Contains(","))
                    {
                        string[] dataStrs = requestValue.Split(',');
                        if (!string.IsNullOrEmpty(dataStrs[0]))
                            condition.AppendFormat(" AND {0}>={1}", ParamName, Convert.ToDouble(dataStrs[0]));
                        if (!string.IsNullOrEmpty(dataStrs[1]))
                            condition.AppendFormat(" AND {0}<={1}", ParamName, Convert.ToDouble(dataStrs[1]));
                    }
                }
                //约定 s_5_开头的使用 IN 号 如request["s_5_STATUS"]
                else if (item.Contains("s_5_") && !string.IsNullOrEmpty(requestValue))
                {
                    ParamName = item.Replace("s_5_", "");//获取字段名称
                    condition.AppendFormat(" AND {0} in ({1})", ParamName, requestValue);
                }
                //约定 s_6_开头的使用 like 号 如request["s_6_EnterpriseName"]，一定要该表维护了对应的拼音字段，默认为该字段加py
                else if (item.Contains("s_6_") && !string.IsNullOrEmpty(requestValue))
                {
                    ParamName = item.Replace("s_6_", "");//获取字段名称
                    condition.AppendFormat(" AND ({0} like '%{1}%' or {0}PY like '%{1}%')", ParamName, requestValue.ToLower());
                }
                else if (item.Contains("s_7_") && !string.IsNullOrEmpty(requestValue))
                {
                    ParamName = item.Replace("s_7_", "");//获取字段名称
                    condition.AppendFormat(" AND {0} {1}", ParamName, requestValue.ToLower());
                }
                else if (item.Contains("s_8_") && !string.IsNullOrEmpty(requestValue))
                {
                    ParamName = item.Replace("s_8_", "");//获取字段名称
                    condition.AppendFormat(" AND {0} > {1} ", ParamName, requestValue.ToLower());
                }
                else if (item.Contains("s_9_") && !string.IsNullOrEmpty(requestValue))
                {
                    ParamName = item.Replace("s_9_", "");//获取字段名称
                    condition.AppendFormat(" AND {0} < {1}", ParamName, requestValue);
                }
                //约定 s_4_开头的使用 数值比较号 如request["s_4_ProjectCost"]
                else if (item.Contains("s_10_") && !string.IsNullOrEmpty(requestValue))
                {
                    ParamName = item.Replace("s_10_", "");//获取字段名称
                    if (requestValue.Contains(","))
                    {
                        string[] dataStrs = requestValue.Split(',');
                        if (!string.IsNullOrEmpty(dataStrs[0]))
                            condition.AppendFormat(" AND {0}>='{1}'", ParamName, dataStrs[0]);
                        if (!string.IsNullOrEmpty(dataStrs[1]))
                            condition.AppendFormat(" AND {0}<='{1}'", ParamName, dataStrs[1]);
                    }
                }
            }
            return condition.ToString();
        }
        public static string GetDateSql(string strStart, string strEnd, string fieldName)
        {
            string returnValue = string.Empty;
            if (!string.IsNullOrEmpty(strStart))
            {
                try
                {
                    DateTime strDate = Convert.ToDateTime(strStart + " 0:00:00");
                    returnValue = string.Format(" AND {0}>='{1}' ", fieldName, strDate.ToString());
                }
                catch (System.Exception)
                {
                }
            }
            if (!string.IsNullOrEmpty(strEnd))
            {
                try
                {
                    DateTime strDate = Convert.ToDateTime(strEnd + " 23:59:59");
                    returnValue += string.Format(" AND {0}<='{1}' ", fieldName, strDate.ToString());
                }
                catch (System.Exception)
                {
                }
            }
            return returnValue;
        }
        public static string GetDaySql(string strStart, string strEnd, string fieldName)
        {
            string returnValue = string.Empty;
            if (!string.IsNullOrEmpty(strStart))
            {
                try
                {
                    DateTime strDate = Convert.ToDateTime(strStart);
                    returnValue = string.Format(" AND {0}>='{1}' ", fieldName, strDate.ToString("yyyy-MM-dd"));
                }
                catch (System.Exception)
                {
                }
            }
            if (!string.IsNullOrEmpty(strEnd))
            {
                try
                {
                    DateTime strDate = Convert.ToDateTime(strEnd);
                    returnValue += string.Format(" AND {0}<'{1}' ", fieldName, strDate.ToString("yyyy-MM-dd"));
                }
                catch (System.Exception)
                {
                }
            }
            return returnValue;
        }

        //只有月份的情况
        public static string GetDaySql2(string strStart, string strEnd, string fieldName)
        {
            string returnValue = string.Empty;
            if (!string.IsNullOrEmpty(strStart))
            {
                try
                {
                    DateTime strDate = Convert.ToDateTime(strStart + "-01");
                    returnValue = string.Format(" AND {0}>='{1}' ", fieldName, strDate.ToString("yyyy-MM-dd"));
                }
                catch (System.Exception)
                {
                }
            }
            if (!string.IsNullOrEmpty(strEnd))
            {
                try
                {
                    DateTime strDate = Convert.ToDateTime(strEnd + "-01");
                    strDate = strDate.AddMonths(1);
                    returnValue += string.Format(" AND {0}<'{1}' ", fieldName, strDate.ToString("yyyy-MM-dd"));
                }
                catch (System.Exception)
                {
                }
            }
            return returnValue;
        }
        public static bool SubmitCheckForm()
        {
            bool result;
            if (HttpContext.Current.Request.Form.Get("txt_hiddenToken").Equals(WebHelper.GetToken()))
            {
                WebHelper.SetToken();
                result = true;
            }
            else
            {
                ShowMsgHelper.showWarningMsg("为了保证表单不重复提交，提交无效");
                result = false;
            }
            return result;
        }

        public static DateTime ParseEndDate(string endDate)
        {
            DateTime newDateTime = Convert.ToDateTime(endDate);
            newDateTime = new DateTime(newDateTime.Year, newDateTime.Month,
                DateTime.DaysInMonth(newDateTime.Year, newDateTime.Month), 23, 59, 59);
            return newDateTime;
        }
        public static string GetToken()
        {
            HttpContext rq = HttpContext.Current;
            string result;
            if (null != rq.Session["Token"])
            {
                result = rq.Session["Token"].ToString();
            }
            else
            {
                result = string.Empty;
            }
            return result;
        }

        public static void SetToken()
        {
            HttpContext rq = HttpContext.Current;
            rq.Session.Add("Token", Md5Helper.MD5(rq.Session.SessionID + DateTime.Now.Ticks.ToString(), 32));
        }

        public string InsertSql(string tableName, Hashtable ht)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(" Insert Into ");
            sb.Append(tableName);
            sb.Append("(");
            StringBuilder sp = new StringBuilder();
            StringBuilder sb_prame = new StringBuilder();
            foreach (string key in ht.Keys)
            {
                sb_prame.Append("," + key);
                sp.Append(",:" + key);
            }
            sb.Append(sb_prame.ToString().Substring(1, sb_prame.ToString().Length - 1) + ") Values (");
            sb.Append(sp.ToString().Substring(1, sp.ToString().Length - 1) + ")");
            return sb.ToString();
        }

        /// <summary>
        /// 获取年月日格式时间
        /// 2016-03-10
        /// </summary>
        /// <param name="date">原数据</param>
        /// <returns></returns>
        public static string GetNewDat(string date)
        {
            string newDate = string.Empty;
            if (!string.IsNullOrEmpty(date))
            {
                //获取年月日
                string date2 = date.Split(' ')[0];
                newDate = date2.Replace('/', '-');
            }
            return newDate;
        }
    }
}